package com.android.namecard.activity;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SlidingDrawer;
import android.widget.ViewSwitcher.ViewFactory;

import com.android.namecard.R;
import com.android.namecard.entity.Namecard;
import com.android.namecard.model.NamecardDBHelper;
import com.android.namecard.util.NamecardViewAdapter;

public class NamecardActivity extends Activity implements ViewFactory, OnGestureListener{
	
	private int index = 0;
	private boolean isLayoutMain = true;
	ImageSwitcher imageSwicher = null;
	BitmapDrawable image[] = new BitmapDrawable[2];
	Namecard namecard = null;
	GestureDetector detector = new GestureDetector(this);
	
	private GridView gv;
	private SlidingDrawer sd;
	private ImageView im;
	private int[] icons={R.drawable.call_phone,R.drawable.send_message,
	                       R.drawable.open_website,R.drawable.search_company,
	                       R.drawable.find_path, R.drawable.group_select, R.drawable.delete};
	private String[] items={"打电话","发信息","打开网址","搜索公司","查找公交路线","更改分组", "删除名片"};
	
	ProgressDialog m_Dialog;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        m_Dialog = ProgressDialog.show(
    			NamecardActivity.this, 
    			"请等待", 
    			"正在为您载入数据...",
    			true);
        
        new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
		        //取得名片id
				prepareData();
	            handler.post(runnable);
			}
        }.start();
    }

	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		return new ImageView(this);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		if (e1.getX() - e2.getX() > 120) {
			Log.i("fling.....", "fling left");
			if(index == 0){
				index = 1;
			}else{
				index = 0;
			}
			if(imageSwicher != null){
				imageSwicher.setImageDrawable(image[index]);
			}
			return true;
		} else if (e1.getX() - e2.getX() < -120) {
			if(index == 0){
				index = 1;
			}else{
				index = 0;
			}
			if(imageSwicher != null){
				imageSwicher.setImageDrawable(image[index]);
			}
			return true;
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return this.detector.onTouchEvent(event);
	}
	
	private Location getMyLocation(){
        //取得LocationManager实例
        LocationManager locationManager;
        String context=Context.LOCATION_SERVICE;
        locationManager=(LocationManager)getSystemService(context);
        //设置Criteria（服务商）的信息
        Criteria criteria =new Criteria();
        //经度要求
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        //取得效果最好的criteria
        String provider=locationManager.getBestProvider(criteria, true);
        //得到坐标相关的信息
        Location location=locationManager.getLastKnownLocation(provider);
        //更新坐标
        //updateWithNewLocation(location);
        //注册一个周期性的更新，3000ms更新一次
        //locationListener用来监听定位信息的改变
        locationManager.requestLocationUpdates(provider, 3000, 0,locationListener);
        return location;
	}
	
	/**
	 * 实例化LocationListener
	 */
	private final LocationListener locationListener = new LocationListener() {  
	    public void onLocationChanged(Location location) { //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发  
	        // log it when the location changes  
	        if (location != null) {  
	            Log.i("SuperMap", "Location changed : Lat: "  
	              + location.getLatitude() + " Lng: "  
	              + location.getLongitude());  
	        }  
	    }  
	  
	    public void onProviderDisabled(String provider) {  
	    // Provider被disable时触发此函数，比如GPS被关闭  
	    }  
	  
	    public void onProviderEnabled(String provider) {  
	    //  Provider被enable时触发此函数，比如GPS被打开  
	    }  
	  
	    public void onStatusChanged(String provider, int status, Bundle extras) {  
	    // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数  
	    }  
	};  
	
	private void prepareData(){
		Bundle bundle = this.getIntent().getExtras();
        String namecardId = bundle.getString("namecardId");
        
        //获取名片详细信息
        NamecardDBHelper namecardDB = new NamecardDBHelper(this.getBaseContext());
        namecard = namecardDB.getNamecardById(namecardId);
        
        //得出名片正反两面
        image[0] = new BitmapDrawable(namecard.getFrontImage());
        image[1] = new BitmapDrawable(namecard.getBackImage());
        
        namecardDB.close();
	}
	
	private void updateUI(){
		
        setContentView(R.layout.namecard);
        
        imageSwicher = (ImageSwitcher)findViewById(R.id.namecard_img_switcher);
        imageSwicher.setFactory(this);
        imageSwicher.setImageDrawable(image[index]);
        
        /* 初始化对象 */
        gv = (GridView)findViewById(R.id.namecard_grid_content); 
        sd = (SlidingDrawer)findViewById(R.id.namecard_drawer);
        im=(ImageView)findViewById(R.id.namecard_open_close);
        
        /* 使用告定义的NamecardViewAdapter设置GridView里面的item内容 */
        NamecardViewAdapter adapter=new NamecardViewAdapter(this,items,icons);
        gv.setAdapter(adapter);
        
        //按钮响应
        gv.setOnItemClickListener(new OnItemClickListener(){
    		public void onItemClick(AdapterView<?> arg0, View arg1, int index,
    				long arg3) {
    			// TODO Auto-generated method stub
    			if(index==0){
    				//拨打电话
					/*建构一个新的Intent并执行action.CALL的常数与透过Uri将字符串带入*/
					Intent myIntentDial = new Intent("android.intent.action.CALL",Uri.parse("tel:"+namecard.getPhone())); 
					/*在startActivity()方法中带入自定义的Intent对象以执行拨打电话的工作*/ 
					startActivity(myIntentDial);
    			}else if(index == 1){
    				//发送短信
    				Intent intent = new Intent(NamecardActivity.this, SendMessageActivity.class);
    				Bundle bundle = new Bundle();
    				bundle.putString("phone", namecard.getPhone());
    				intent.putExtras(bundle);
    				startActivity(intent);
    			}else if(index == 2){
    				//打开网页
    				try{
    					Uri uri= Uri.parse(namecard.getWebsite());
        				Intent intent = new Intent(Intent. ACTION_VIEW , uri );
                        startActivity(intent);
    				}catch(Exception e){
    					Log.i("open the website error:", e.toString());
    					Toast.makeText(getApplicationContext(), "网址有错,无法打开", Toast.LENGTH_SHORT).show();
    				}
    				
    			}else if(index == 3){
    				//搜索公司
    				Intent search = new Intent(Intent.ACTION_WEB_SEARCH); 
    				search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    				search.putExtra(SearchManager.QUERY, namecard.getCompany()); 
    				Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA); 
    				if (appData != null) { 
    				    search.putExtra(SearchManager.APP_DATA, appData); 
    				} 
                    startActivity(search);
    			}else if(index == 4){
    				//查找公交路线
    				try{
	    				//获取自己的位置
	    				Location location = getMyLocation();
	    				double myLatitude = location.getLatitude();//经度
	    				double myLongitude = location.getLongitude();//纬度
	    				double myAltitude = location.getAltitude();//海拔
	    				
	    				//获取名片所有者的位置
	    				Geocoder geo = new Geocoder(getBaseContext(), Locale.CHINA);
	    				List addresses = null;
	    				
	    				addresses = geo.getFromLocationName(namecard.getAddress(), 1);
	    				
	    				Address address = null;
	    				double heLatitude = 0;//经度
	    				double heLongitude = 0;//纬度
	    				double heAltitude = 0;//海拔
	    				if(addresses.size()!=0 && addresses!=null){
	    					address = (Address) addresses.get(0);
	    					heLatitude = address.getLatitude();
	    					heLongitude = address.getLongitude();
	    					Log.i("The Latitude is:" , String.valueOf(address.getLatitude()));
	    					Log.i("The Longitude is:" , String.valueOf(address.getLongitude()));
	    				}
	    				
	    				String uriString = "http://ditu.google.cn/maps?f=d&source=s_d&saddr="+myLatitude + "," + myLongitude +
	    					"&daddr=" + heLatitude + "," + heLongitude + "&hl=zh";
	    				Uri uri = Uri.parse(uriString);
	    				Intent i = new Intent(Intent.ACTION_VIEW, uri); 
	    		        startActivity(i); 
                    }catch(Exception e){
                    	Log.i("open the path error:", e.toString());
    					Toast.makeText(getApplicationContext(), "地址有错或者地址为空，无法查询路径!", Toast.LENGTH_SHORT).show();
    				}
    			}else if(index == 5){
    				//更改分组
    				Intent intent = new Intent(NamecardActivity.this, ChangeGroupActivity.class);
    				Bundle bundle = new Bundle();
    				bundle.putString("namecardId", namecard.getNamecardId());
    				bundle.putString("type", namecard.getType());
    				intent.putExtras(bundle);
    				startActivity(intent);
    			}else if(index == 6){
    				//删除名片
    				Dialog dialog = new AlertDialog.Builder(NamecardActivity.this)
    				    .setTitle("温馨提醒")
    				    .setMessage("您确定要删除此名片吗？")
    				    .setPositiveButton("确定", 
    				    		new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
					    				NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
					    				namecardDB.deleteNamecardById(namecard.getNamecardId());
					    				NamecardActivity.this.setResult(0);
					    				NamecardActivity.this.finish();
					    				
									}
								})
						.setNegativeButton("取消", 
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										
									}
								}).create();
    				dialog.show();
    			}
    		}
    		
        });
        
        /* 设定SlidingDrawer被打开的事件处理 */
        sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener(){
            @Override
            public void onDrawerOpened(){
            	im.setImageResource(R.drawable.close);
            }
        });
        /* 设置SlidingDrawer被关闭的事件处理 */
        sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener(){
            @Override
            public void onDrawerClosed(){
            	im.setImageResource(R.drawable.open);
            }
        });
	}
	
	final Handler handler = new Handler();
	
	final Runnable runnable = new Runnable(){
		@Override
		public void run() {
			// TODO Auto-generated method stub
			updateUI();
			m_Dialog.dismiss();
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			NamecardActivity.this.setResult(0);
			NamecardActivity.this.finish();
			return true;
		}
		return false;
	}
}
